//
//  TargetLevelView.m
//  BondWatch
//
//  Created by Jason Yuan on 2/25/16.
//  Copyright © 2016 Jason Yuan. All rights reserved.
//

#import "TargetLevelView.h"
#import "TargetLevel.h"

#define TitleFont [UIFont fontWithName:@"Arial-BoldMT" size:11.0];
#define TargetFont [UIFont fontWithName:@"Arial-BoldMT" size:12.0];

@implementation TargetLevelView 

@synthesize targetLevelView;
@synthesize titleLabel1;
@synthesize titleLabel2;
@synthesize targetLabel;
@synthesize thresholdLabel;
@synthesize typeLabel;
@synthesize targetField;
@synthesize thresholdField;
@synthesize typeField;
@synthesize leftButton;
@synthesize rightButton;
@synthesize bottomButton;
@synthesize buttonView;
@synthesize finishButton;
@synthesize typePickView;
@synthesize typeArray;
@synthesize dataArray;
@synthesize currentIndexPath;
@synthesize delegate;

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
    targetLevelView = [[UIView alloc] init];
    targetLevelView.backgroundColor = [UIColor whiteColor];
    targetLevelView.layer.cornerRadius = 15.0f;
    targetLevelView.layer.borderColor = [[UIColor blackColor] CGColor];
    targetLevelView.layer.borderWidth = 1.0f;
    [self addSubview:targetLevelView];
    
    [targetLevelView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(targetLevelView.superview);
        make.centerY.equalTo(targetLevelView.superview).offset(-100);
        make.size.mas_equalTo(CGSizeMake(240, 210));
    }];
    
    titleLabel1 = [[UILabel alloc] init];
    titleLabel1.text = @"Title";
    titleLabel1.textAlignment = NSTextAlignmentCenter;
    titleLabel1.font = TitleFont;
    [targetLevelView addSubview:titleLabel1];
    
    [titleLabel1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel1.superview).offset(5);
        make.left.equalTo(titleLabel1.superview);
        make.right.equalTo(titleLabel1.superview);
        make.height.mas_equalTo(20);
    }];
    
    titleLabel2 = [[UILabel alloc] init];
    titleLabel2.text = @"Title";
    titleLabel2.textAlignment = NSTextAlignmentCenter;
    titleLabel2.font = TitleFont;
    titleLabel2.textColor = SUMRIDGECOLOR;
    [targetLevelView addSubview:titleLabel2];
    
    [titleLabel2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel1.mas_bottom);
        make.left.equalTo(titleLabel2.superview);
        make.right.equalTo(titleLabel2.superview);
        make.height.mas_equalTo(20);
    }];
    
    targetLabel = [[UILabel alloc] init];
    targetLabel.text = @"Target: ";
    targetLabel.font = TargetFont;
    [targetLevelView addSubview:targetLabel];
    
    [targetLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel2.mas_bottom).offset(10);
        make.left.equalTo(targetLabel.superview).offset(10);
        make.size.mas_equalTo(CGSizeMake(80, 20));
    }];
    
    targetField = [[UITextField alloc] init];
    targetField.tag = 1;
    targetField.keyboardType = UIKeyboardTypeDecimalPad;
    targetField.font = TargetFont;
    targetField.textColor = SUMRIDGECOLOR;
    targetField.borderStyle = UITextBorderStyleRoundedRect;
    targetField.clearButtonMode = UITextFieldViewModeWhileEditing;
    targetField.layer.borderColor = SUMRIDGECOLOR.CGColor;
    targetField.delegate = self;
    [targetLevelView addSubview:targetField];
    
    [targetField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel2.mas_bottom).offset(10);
        make.left.equalTo(targetField.superview).offset(90);
        make.size.mas_equalTo(CGSizeMake(120, 20));
    }];
    
    thresholdLabel = [[UILabel alloc] init];
    thresholdLabel.text = @"Threshold: ";
    thresholdLabel.font = TargetFont;
    [targetLevelView addSubview:thresholdLabel];
    
    [thresholdLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(targetLabel.mas_bottom).offset(10);
        make.left.equalTo(thresholdLabel.superview).offset(10);
        make.size.mas_equalTo(CGSizeMake(80, 20));
    }];
    
    thresholdField = [[UITextField alloc] init];
    thresholdField.tag = 2;
    thresholdField.keyboardType = UIKeyboardTypeDecimalPad;
    thresholdField.font = TargetFont;
    thresholdField.textColor = SUMRIDGECOLOR;
    thresholdField.borderStyle = UITextBorderStyleRoundedRect;
    thresholdField.clearButtonMode = UITextFieldViewModeWhileEditing;
    thresholdField.layer.borderColor = SUMRIDGECOLOR.CGColor;
    thresholdField.text = @"0.1";
    thresholdField.delegate = self;
    [targetLevelView addSubview:thresholdField];
    
    [thresholdField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(targetLabel.mas_bottom).offset(10);
        make.left.equalTo(thresholdField.superview).offset(90);
        make.size.mas_equalTo(CGSizeMake(120, 20));
    }];
    
    typeLabel = [[UILabel alloc] init];
    typeLabel.text = @"Type: ";
    typeLabel.font = TargetFont;
    [targetLevelView addSubview:typeLabel];
    
    [typeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(thresholdLabel.mas_bottom).offset(10);
        make.left.equalTo(typeLabel.superview).offset(10);
        make.size.mas_equalTo(CGSizeMake(80, 20));
    }];
    
    typeField = [[UITextField alloc] init];
    typeField.tag = 3;
    typeField.font = TargetFont;
    typeField.textColor = SUMRIDGECOLOR;
    typeField.borderStyle = UITextBorderStyleRoundedRect;
    typeField.clearButtonMode = UITextFieldViewModeWhileEditing;
    typeField.layer.borderColor = SUMRIDGECOLOR.CGColor;
    typeField.text = @"Price";
    typeField.delegate = self;
    [targetLevelView addSubview:typeField];
    
    [typeField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(thresholdLabel.mas_bottom).offset(10);
        make.left.equalTo(typeField.superview).offset(90);
        make.size.mas_equalTo(CGSizeMake(120, 20));
    }];
    
    leftButton  = [UIButton buttonWithType:UIButtonTypeSystem];
    leftButton.titleLabel.font = TargetFont;
    leftButton.layer.cornerRadius = 5.0;
    leftButton.layer.borderWidth = 1.0f;
    [leftButton setBackgroundColor:SUMRIDGECOLOR];
    [leftButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [leftButton setTitle:@"Save" forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(setTargetLevel:) forControlEvents:UIControlEventTouchUpInside];
    [targetLevelView addSubview:leftButton];
    [leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(leftButton.superview).offset(10);
        make.top.equalTo(typeField.mas_bottom).offset(20);
        make.size.mas_equalTo(CGSizeMake(90, 20));
    }];
    
    rightButton = [UIButton buttonWithType:UIButtonTypeSystem];
    rightButton.titleLabel.font = TargetFont;
    rightButton.layer.cornerRadius = 5.0;
    rightButton.layer.borderWidth = 1.0f;
    [rightButton setBackgroundColor:SUMRIDGECOLOR];
    [rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rightButton setTitle:@"Remove Target" forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(removeTargetLevel:) forControlEvents:UIControlEventTouchUpInside];
    [targetLevelView addSubview:rightButton];
    [rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(leftButton.mas_right).offset(10);
        make.top.equalTo(typeField.mas_bottom).offset(20);
        make.size.mas_equalTo(CGSizeMake(120, 20));
    }];
    
    bottomButton = [UIButton buttonWithType:UIButtonTypeSystem];
    bottomButton.titleLabel.font = TargetFont;
    bottomButton.layer.cornerRadius = 5.0;
    bottomButton.layer.borderWidth = 1.0f;
    [bottomButton setBackgroundColor:SUMRIDGECOLOR];
    [bottomButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [bottomButton setTitle:@"Cancel" forState:UIControlStateNormal];
    [bottomButton addTarget:self action:@selector(closeTargetView:) forControlEvents:UIControlEventTouchUpInside];
    [targetLevelView addSubview:bottomButton];
    [bottomButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bottomButton.superview).offset(10);
        make.right.equalTo(bottomButton.superview).offset(-10);
        make.top.equalTo(leftButton.mas_bottom).offset(10);
        make.height.mas_equalTo(20);
    }];
    
    typeArray = @[@"Price", @"Yield", @"Spread"];
    
    typePickView = [[UIPickerView alloc] init];
    typePickView.hidden = YES;
    typePickView.dataSource = self;
    typePickView.delegate = self;
    [self addSubview:typePickView];
    
    [typePickView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(typePickView.superview);
        make.right.equalTo(typePickView.superview);
        make.bottom.equalTo(typePickView.superview).offset(-40);
        make.height.mas_equalTo(200);
    }];
    
    buttonView = [[UIView alloc] init];
    buttonView.hidden = YES;
    [buttonView setBackgroundColor:[UIColor colorWithRed:1 green:1 blue:1 alpha:0.5]];
    [self addSubview:buttonView];
    
    [buttonView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(buttonView.superview);
        make.right.equalTo(buttonView.superview);
        make.bottom.equalTo(buttonView.superview).offset(-160);
        make.height.mas_equalTo(30);
    }];
    
    finishButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [finishButton setTitle:@"Finish" forState:UIControlStateNormal];
    [finishButton addTarget:self action:@selector(finishButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [buttonView addSubview:finishButton];
    [finishButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(finishButton.superview);
        make.centerY.equalTo(finishButton.superview);
        make.size.mas_equalTo(CGSizeMake(80, 20));
    }];
}

- (void)setTargetLevel:(id)sender {
    int type;
    
    if ([typePickView selectedRowInComponent:0] == 0) {
        type = 0;
    } else if ([typePickView selectedRowInComponent:0] == 1) {
        type = 3;
    } else {
        type = 6;
    }
    
    NSDictionary *params = @{
                             @"prwId" : [Shared shared].prwId,
                             @"secid" : [TargetLevel sharedInstance].cusip,
                             @"target" : targetField.text,
                             @"threshold" : thresholdField.text,
                             @"type" : [NSNumber numberWithInt:type]
                             };
    
    [MBProgressHUD showHUDAddedTo:self animated:YES].dimBackground = YES;
    AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
    [requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = requestSerializer;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    [manager POST:SETTARGETLEVEL parameters:params success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [MBProgressHUD hideHUDForView:self animated:YES];
        NSNumber *success = [responseObject objectForKey:@"success"];
        DDLogVerbose(@"Set target level result: %@", success);
        
        if ([success intValue] == 1) {
            [targetField resignFirstResponder];
            [thresholdField resignFirstResponder];
            NSMutableDictionary *dictionary = [dataArray objectAtIndex:currentIndexPath.row];
            [dictionary setValue:targetField.text forKey:@"target"];
            [self closeTargetView:nil];
            [delegate reloadTableView:currentIndexPath];
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self animated:YES];
            hud.mode = MBProgressHUDModeText;
            hud.labelText = @"Set Success.";
            
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                // Do something...
                [MBProgressHUD hideHUDForView:self animated:YES];
            });
        } else {
            [targetField resignFirstResponder];
            [thresholdField resignFirstResponder];
            [self closeTargetView:nil];
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self animated:YES];
            hud.mode = MBProgressHUDModeText;
            hud.labelText = @"Set Failure.";
            
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                // Do something...
                [MBProgressHUD hideHUDForView:self animated:YES];
            });
        }
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        [targetField resignFirstResponder];
        [thresholdField resignFirstResponder];
        [self closeTargetView:nil];
        if (operation.response.statusCode == 200) {
            [delegate sessionTimeOut];
            return;
        }
        
        DDLogError(@"Set target level error:\n%@", error);
        [MBProgressHUD hideHUDForView:self animated:YES];
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"Network Error.";
        hud.detailsLabelText = @"Please retry later.";
        
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            // Do something...
            [MBProgressHUD hideHUDForView:self animated:YES];
        });
    }];
}

- (void)removeTargetLevel:(id)sender {
    int type;
    
    if ([typePickView selectedRowInComponent:0] == 0) {
        type = 0;
    } else if ([typePickView selectedRowInComponent:0] == 1) {
        type = 3;
    } else {
        type = 6;
    }
    
    NSDictionary *params = @{
                             @"prwId" : [Shared shared].prwId,
                             @"secid" : [TargetLevel sharedInstance].cusip,
                             @"target" : @"",
                             @"threshold" : thresholdField.text,
                             @"type" : [NSNumber numberWithInt:type]
                             };
    
    [MBProgressHUD showHUDAddedTo:self animated:YES].dimBackground = YES;
    AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
    [requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = requestSerializer;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    [manager POST:SETTARGETLEVEL parameters:params success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [MBProgressHUD hideHUDForView:self animated:YES];
        NSNumber *success = [responseObject objectForKey:@"success"];
        DDLogVerbose(@"Set target level result: %@", success);
        
        if ([success intValue] == 1) {
            [targetField resignFirstResponder];
            [thresholdField resignFirstResponder];
            NSDictionary *dictionary = [dataArray objectAtIndex:currentIndexPath.row];
            [dictionary setValue:[NSNull null] forKey:@"target"];
            [self closeTargetView:nil];
            [delegate reloadTableView:currentIndexPath];
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self animated:YES];
            hud.mode = MBProgressHUDModeText;
            hud.labelText = @"Remove Success.";
            
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                // Do something...
                [MBProgressHUD hideHUDForView:self animated:YES];
            });
        } else {
            [targetField resignFirstResponder];
            [thresholdField resignFirstResponder];
            [self closeTargetView:nil];
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self animated:YES];
            hud.mode = MBProgressHUDModeText;
            hud.labelText = @"Remove Failure.";
            
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                // Do something...
                [MBProgressHUD hideHUDForView:self animated:YES];
            });
        }
        
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        [targetField resignFirstResponder];
        [thresholdField resignFirstResponder];
        [self closeTargetView:nil];
        if (operation.response.statusCode == 200) {
            [delegate sessionTimeOut];
            return;
        }
        
        DDLogError(@"Set target level error:\n%@", error);
        [MBProgressHUD hideHUDForView:self animated:YES];
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"Network Error.";
        hud.detailsLabelText = @"Please retry later.";
        
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            // Do something...
            [MBProgressHUD hideHUDForView:self animated:YES];
        });
    }];
}

- (void)closeTargetView:(id)sender {
    self.hidden = YES;
    typePickView.hidden = YES;
    buttonView.hidden = YES;
    [delegate reloadTableView:currentIndexPath];
    [targetField resignFirstResponder];
    [thresholdField resignFirstResponder];
}

- (void)finishButtonPressed:(id)sender {
    typePickView.hidden = YES;
    [targetField resignFirstResponder];
    [thresholdField resignFirstResponder];
}

#pragma mark - Text field delegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField.tag == 3) {
        [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
        buttonView.hidden = NO;
        typePickView.hidden = NO;
        return NO;
    } else {
        return YES;
    }
}

#pragma mark - Picker view data source

// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return [typeArray count];
}

#pragma mark - Picker view delegate

//- (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
//    return [typeArray objectAtIndex:row];
//}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(nullable UIView *)view {
    UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, self.bounds.size.width, 20)];
    textLabel.text = [typeArray objectAtIndex:row];
    textLabel.textColor = [UIColor colorWithRed:46.0/255.0 green:117.0/255.0 blue:254.0/255.0 alpha:1.0];
    textLabel.textAlignment = NSTextAlignmentCenter;
    textLabel.font = TargetFont;
    return textLabel;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component  {
    typeField.text = [typeArray objectAtIndex:row];
}

@end
